package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 老人家属Service业务层处理
 *
 * @author Lorine
 * @date 2025-03-03
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好", "大桔大利", "日富一日", "好柿开花", "柿柿如意", "一椰暴富", "大柚所为", "杨梅吐气", "天生荔枝");
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private TokenService tokenService;


    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //根据code获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        //根据openId查询数据库用户信息
        FamilyMember member = this.getOne(new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getOpenId, openId));
        //如果用户不存在,创建新用户
        if (ObjectUtil.isNull(member)) {
            member = new FamilyMember();
            member.setOpenId(openId);
        }
        //根据phoneCode查询用户信息
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //更新或新增用户
        insertOrUpdate(member, phone);
        //生成jwt令牌
        String token = getToken(member);
        //返回用户信息
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        loginVo.setToken(token);
        return loginVo;
    }

    private String getToken(FamilyMember member) {
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", member.getId());
        claims.put("nickName", member.getName());
        return tokenService.createToken(claims);
    }

    private void insertOrUpdate(FamilyMember member, String phone) {
        if (ObjectUtil.isNull(member.getId())) {
            //如果id不存在,新增用户
            member.setPhone(phone);
            member.setName(DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size())) + member.getPhone().substring(7));
            this.save(member);
        } else if (!phone.equals(member.getPhone())) {
            //如果手机号不相同,更新用户
            member.setPhone(phone);
            this.updateById(member);
        }
    }
}
